﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iLangl.Model;
using iLangl.Customer;
using iLangl.Customer.DAL;
using iLangl;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Entities.Content;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;
using iLangl.Customer.Managers;


namespace iLangl.Customer.DNN.Managers
{
	public class ProjectManagerDNN : ProjectManager
	{
		#region Singelton Pattern


		private static ProjectManagerDNN instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the ProjectManager.
		/// </summary>
		public static ProjectManagerDNN Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new ProjectManagerDNN();
							
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public void LockProject(Project project)
		{
			IList<ModuleInfo> modules = new List<ModuleInfo>();
			IList<TabInfo> tabs = new List<TabInfo>();

			IList<CustomerContentEntity> permissionsToSave = new List<CustomerContentEntity>();
			foreach (ContentEntity ce in project.Contents)
			{
				CustomerContentEntity cce = new CustomerContentEntity();
				cce.Id = ce.Id;

				ContentItem ci = (ContentItem)IdentityManager.GetContent(ce.CustomerIdentity);
				if (ci is ModuleInfo)
				{
					ModuleInfo mi = ci as ModuleInfo;
					cce.Permissions = PermissionManager.ExportModulePermissions(mi.ModulePermissions);
					modules.Add(mi);
				}
				if (ci is TabInfo)
				{
					TabInfo tab = ci as TabInfo;
					cce.Permissions = PermissionManager.ExportTabPermissions(tab.TabPermissions);
					tabs.Add(ci as TabInfo);
				}
				permissionsToSave.Add(cce);
			}

			DALFacade.Instance.ContentDAL.SaveContentPermissions(permissionsToSave);
			SecurityManager.Instance.LockContent(modules);
			SecurityManager.Instance.LockContent(tabs);
		}

		public void UnlockProject(Project project)
		{
			IList<CustomerContentEntity> projectcontents= DALFacade.Instance.ContentDAL.ReadContentByProject(project);
			SecurityManager.Instance.UnlockContent(projectcontents);
		}

		public CustomerProject[] GetProjectsByStatus(String Status)
		{
			return DALFacade.Instance.ProjectDAL.GetProjectsByStatus(Status);
		}

		public CustomerProject NewProject()
		{
			CustomerProject project = new CustomerProject();
			project.Id = Guid.NewGuid().ToString();
			project.Status = ProjectStatuses.Configuration;
			return project;
		}


		public CustomerProject GetProjectByName(string projectTitle)
		{
			return DALFacade.Instance.ProjectDAL.GetProjectByName(projectTitle);
		}
	}
}